import React, { useContext, useState } from 'react';
import { Alert, View, ScrollView, StatusBar } from 'react-native';
import { Button, Divider, Icon, Input, Text } from 'react-native-elements';

import CryptoJS from 'crypto-js';

import LocaleContext from '../libs/locale';
import { keyPairFromSeed, toAddress } from '../libs/keyPair';
import { Wallet } from '../libs/wallet';
import AsyncStorage from "@react-native-async-storage/async-storage";

const Import = ({ navigation, setWallet }: any) => {
  const locale = useContext(LocaleContext);
  const [isKeystore, setIsKeystore] = useState(true);

  const onNewWallet = async (wallet: Wallet) => {
      setWallet(wallet);
      await AsyncStorage.setItem('@wallet_address', wallet.address)
      navigation.reset({index: 0, routes: [{name: 'Normal'}]});
  };

  return (
    <ScrollView>
      <StatusBar barStyle='dark-content' translucent={false} backgroundColor="#FAFBFDFF" />
      <View>
        <View style={{
          flexDirection: 'row',
          justifyContent: 'space-around',
          marginTop: 20
        }}>
          <View style={{ alignItems: 'center' }}>
            <Text
              style={{
                fontSize: 16,
                fontWeight: 'bold',
                paddingBottom: 10,
                ...isKeystore ? { color: '#7259E0FF' } : {}
              }}
              onPress={() => setIsKeystore(true)}
            >{locale?._('Import.keyStore')}</Text>
            {
              isKeystore ?
                <Divider style={{
                  borderColor: '#7259E0FF',
                  borderWidth: 1.2,
                  width: 30
                }} />
                : <></>
            }
          </View>
          <View style={{ alignItems: 'center' }}>
            <Text
              style={{
                fontSize: 16,
                fontWeight: 'bold',
                paddingBottom: 10,
                ...!isKeystore ? { color: '#7259E0FF' } : {}
              }}
              onPress={() => setIsKeystore(false)}
            >{locale?._('Import.privateKey')}</Text>
            {
              !isKeystore ?
                <Divider style={{
                  borderColor: '#7259E0FF',
                  borderWidth: 1.2,
                  width: 30
                }} />
                : <></>
            }
          </View>
        </View>
        <Divider style={{ marginLeft: 10, marginRight: 10 }} />
      </View>

      {
        isKeystore ?
          <ImportKeystore onNewWallet={onNewWallet} /> :
          <ImportPrivatekey onNewWallet={onNewWallet} />
      }
    </ScrollView>
  );
};

const ImportPrivatekey = ({ onNewWallet }: any) => {
  const locale = useContext(LocaleContext);
  const [key, setKey] = useState('');
  const [pwdVisible, setPwdVisible] = useState(false);
  const [pwdVisible2, setPwdVisible2] = useState(false);
  const [memo, setMemo] = useState('');
  const [pwd, setPwd] = useState('');
  const [pwd2, setPwd2] = useState('');

  const onImport = async () => {
    if (!key) {
      Alert.alert('', `${locale?._('enter')} ${locale?._('Import.privateKey')}`);
      return;
    }
    if(key.length!==64 && key.length!==128)
    {
        Alert.alert('', `${locale?._('Import.correctPrivatekey')}`);
        return;
    }

    // if (!memo) {
    //   Alert.alert('', `${locale?._('enter')} ${locale?._('Register.memo')}`);
    //   return;
    // }
    if (!pwd.length) {
      Alert.alert('', `${locale?._('enter')} ${locale?._('Import.password')}`);
      return;
    }
    // if (pwd.length < 6 || pwd.length > 12) {
    //   Alert.alert('', locale?._('Register.passwordError'));
    //   return;
    // }
    if (pwd !== pwd2) {
      Alert.alert('', locale?._('Register.repasswordError'));
      return;
    }

    const keyPair = keyPairFromSeed(key);
    if (!keyPair) {
      Alert.alert('', `${locale?._('Import.privateKey')} ${locale?._('Import.invalid')}`);
      return;
    }

    const address = toAddress(keyPair.publicKey);
    const encrypted = CryptoJS.AES.encrypt(key, pwd).toString();

    onNewWallet({ encrypted, seed: key, address, memo, exported: true });

    await AsyncStorage.setItem('@wallet_address', address)
  };

  return (
    <View>
      <View style={{ marginLeft: 14, marginRight: 14, marginTop: 26 }}>
        <Input
          placeholder={`${locale?._('enter')} ${locale?._('Import.privateKey')}`}
          onChangeText={value => setKey(value.trim())}
          numberOfLines={5}
          multiline={true}
          inputContainerStyle={{ borderBottomWidth: 0 }}
          style={{
            borderWidth: 1,
            borderColor: '#BFBFBFFF',
            borderRadius: 6,
            backgroundColor: '#F8FAFCFF',
            textAlign: 'center',
          }}
        />
      </View>

      <View style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'stretch',
        paddingLeft: 16,
        paddingRight: 16,
        marginBottom: 6,
      }}>
        {/* <Input
          placeholder={locale?._('Register.memo')}
          onChangeText={value => setMemo(value.trim())}
        /> */}
        <Input
          placeholder={locale?._('Register.passwordPlaceholder')}
          rightIcon={<Icon
            name={pwdVisible ? 'eye' : 'eye-off'}
            type='feather'
            onPress={() => setPwdVisible(!pwdVisible)}
          />}
          secureTextEntry={!pwdVisible}
          onChangeText={value => setPwd(value)}
        />
        <Input
          placeholder={locale?._('Register.repassword')}
          rightIcon={<Icon
            name={pwdVisible2 ? 'eye' : 'eye-off'}
            type='feather'
            onPress={() => setPwdVisible2(!pwdVisible2)}
          />}
          secureTextEntry={!pwdVisible2}
          onChangeText={value => setPwd2(value)}
        />
      </View>
      <View style={{
        display: 'flex',
        alignItems: 'center',
      }}>
        <Button
          title={locale?._('Guest.import')}
          onPress={onImport}
          buttonStyle={{ backgroundColor: '#7460E3FF' }}
        />

      </View>
    </View>
  );
};

const ImportKeystore = ({ onNewWallet }: any) => {
  const locale = useContext(LocaleContext);
  const [key, setKey] = useState('');
  const [pwdVisible, setPwdVisible] = useState(false);
  const [memo, setMemo] = useState('');
  const [pwd, setPwd] = useState('');

  const onImport = async () => {
    if (!key) {
      Alert.alert('', `${locale?._('enter')} Keystore`);
      return;
    }

    // if (!memo) {
    //   Alert.alert('', `${locale?._('enter')} ${locale?._('Register.memo')}`);
    //   return;
    // }
    if (!pwd.length) {
      Alert.alert('', `${locale?._('enter')} ${locale?._('Import.password')}`);
      return;
    }

    const invalid = `Keystore ${locale?._('Import.invalid')}`;

    try {
      var ks = JSON.parse(key);
    } catch (e) {
      Alert.alert('', invalid);
      return;
    }

    if (!Array.isArray(ks.accounts) || ks.accounts.length === 0) {
      Alert.alert('', invalid);
      return;
    }

    const { address, encrypted } = ks.accounts[0];

    try {
      var seed = CryptoJS.AES.decrypt(encrypted, pwd).toString(CryptoJS.enc.Utf8);
    } catch (e) {
      // ignore
    }
    if (!seed) {
      Alert.alert('', locale?._('Import.passwordError'));
      return;
    }

    const keyPair = keyPairFromSeed(seed);
    if (!keyPair || toAddress(keyPair.publicKey) !== address) {
      Alert.alert('', invalid);
      return;
    }

    onNewWallet({ encrypted, seed, address, memo, exported: true });
  };

  return (
    <View>
      <View style={{ marginLeft: 14, marginRight: 14, marginTop: 26 }}>
        <Input
          placeholder={`${locale?._('enter')} Keystore`}
          onChangeText={value => setKey(value.trim())}
          numberOfLines={5}
          multiline={true}
          inputContainerStyle={{ borderBottomWidth: 0 }}
          style={{
            borderWidth: 1,
            borderColor: '#BFBFBFFF',
            borderRadius: 6,
            backgroundColor: '#F8FAFCFF',
            textAlign: 'center',
          }}
        />
      </View>

      <View style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'stretch',
        paddingLeft: 16,
        paddingRight: 16,
        marginBottom: 6,
      }}>
        {/* <Input
          placeholder={locale?._('Register.memo')}
          onChangeText={value => setMemo(value.trim())}
        /> */}
        <Input
          placeholder={locale?._('Import.password')}
          rightIcon={<Icon
            name={pwdVisible ? 'eye' : 'eye-off'}
            type='feather'
            onPress={() => setPwdVisible(!pwdVisible)}
          />}
          secureTextEntry={!pwdVisible}
          onChangeText={value => setPwd(value)}
        />
      </View>
      <View style={{
        display: 'flex',
        alignItems: 'center',
      }}>
        <Button
          title={locale?._('Guest.import')}
          onPress={onImport}
          buttonStyle={{ backgroundColor: '#7460E3FF' }}
        />

      </View>
    </View>
  );
};

export default Import;
